<template>
  <div>
    <a-drawer
      title="核对入帐"
      :width="720"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="close"
    >
      <a-form ref="formRef" :model="formState" :rules="formRules" layout="vertical" hide-required-mark>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="收入" name="income" :rules="formRules.income">
              <a-input readonly
                v-model:value="formState.income"
                :style="{ width: '100%' }"
                addon-before="￥"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="支出" name="expenditure" :rules="formRules.expenditure">
              <a-input readonly
                v-model:value="formState.expenditure"
                :style="{ width: '100%' }"
                addon-before="￥"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="总单数" name="total" :rules="formRules.total">
              <a-input readonly
                v-model:value="formState.total"
                :style="{ width: '100%' }"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="利润" name="profit" :rules="formRules.profit">
              <a-input
                readonly
                v-model:value="formState.profit"
                :style="{ width: '100%' }"
                addon-before="￥"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="客户" name="id_client" :rules="formRules.id_client">
              <a-select
                v-model:value="formState.id_client"
                disabled
                allowClear
                showSearch
                optionFilterProp="children"
                :options="clients">
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="入帐公司" name="id_company" :rules="formRules.id_company">
              <a-select
                showSearch
                v-model:value="formState.id_company">
                <a-select-option v-for="c of companies" :key="c.value" :value="c.value">{{c.label}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="入帐日期" name="accounted_date" :rules="formRules.accounted_date">
              <a-date-picker
                :value-format="dateFormat"
                v-model:value="formState.accounted_date"
                :style="{ width: '100%' }"
                :get-popup-container="trigger => trigger.parentNode"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="备注" name="memo" :rules="formRules.memo">
              <a-textarea
                v-model:value="formState.memo"
                :rows="4"
                placeholder="Please enter your description in case you forget something!"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }">
        <a-button :style="{ marginRight: '8px' }" @click="close"> 取消</a-button>
        <a-button type="primary" @click="handleOk">提交</a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import moment from 'moment'
import _, { pick } from "lodash";
import { postAction } from "@/utils/request";
import { message } from 'ant-design-vue';
import {isNumber, labelDict} from "@/utils/my.js";

const formRef = ref(null); // 表单引用

// 定义 props
const props = defineProps(['clients', 'companies']);

// 响应式数据
const dateFormat = ref('YYYY-MM-DD');
const visible = ref(false);
////reactive+refs 初始化表单数据
const initFormData = {
  id: undefined,
  income: undefined,
  expenditure: undefined,
  total: undefined,
  profit: undefined,
  id_client: undefined,
  id_trade_partner: undefined,
  id_company: undefined,
  accounted_date: undefined,
  memo: undefined
}
const data = reactive({
  formState: Object.assign({}, initFormData)
});
const { formState } = toRefs(data);

// 定义表单验证规则
const validateNumber = (rule, value) => {
  if (!isNumber(value))
    return Promise.reject(`利润必须是数字！`);
  if (value-0<=0)
    return Promise.reject(`利润必须大于0！`);
  return Promise.resolve(); // 验证通过
};
const formRules = ref({
  income: [
    { required: true, message: '收入不能为空', trigger: 'blur' }
  ],
  expenditure: [
    { required: true, message: '支出不能为空', trigger: 'blur' }
  ],
  total: [
    { required: true, message: '总单数不能为空', trigger: 'blur' }
  ],
  profit: [
    { required: true, message: '利润不能为空', trigger: 'blur' },
    { type: 'method', validator: validateNumber, trigger: 'blur'}
  ],
  id_client: [
    { required: true, message: '客户不能为空', trigger: 'blur' }
  ],
  id_company: [
    { required: true, message: '入帐公司不能为空', trigger: 'blur' }
  ],
  accounted_date: [
    { required: true, message: '入帐日期不能为空', trigger: 'blur' }
  ],
  memo: []
});
// simple vars
const url = {
  saveCheckedBillRecord: '/yg/finance/saveCheckedBillRecord',
}

// methods
// 设置新的初始值
const setInitialValues = () => {
    // 重置到新设置的值
    Object.assign(formState.value, initFormData)
    // 清除校验结果
    formRef.value.resetFields();
    console.log('已设置新的初始值并重置');
};
// 核对帐单函数
const showBillToCheck = async (param) => {
    visible.value = true;
    //console.log("param:", JSON.stringify(param));
    await nextTick(() => {
        //setInitialValues()
        formState.value = {
          accounted_date: moment(new Date()).format("YYYY-MM-DD"),
          ...pick(param, ['id_client', 'id_company', 'income', 'id_trade_partner',
                    'expenditure', 'profit', 'total', 'id_checked_bills', 'update_by'])
        };
    });
};
const emit = defineEmits(['sync'])
// 保存函数
const save = () => {
  postAction(url.saveCheckedBillRecord, formState.value).then(response => {
    //console.error("id:",response.data.id)
    if (response.data && response.data.id > 0) {
      formState.value.id = response.data.id;
      message.success("保存成功");
      close()
      emit("sync",1)
    } else {
      message.error("保存失败");
    }
  })
      .catch(error => {
        message.error("保存失败");
        console.log('error', error);
      });
};
// 处理提交函数
const handleOk = async () => {
    await nextTick(() => {
      formRef.value?.validate()
          .then(() => {
            save(formState.value)
          })
          .catch(error => {
            message.warning("表单信息验证失败");
            console.log('error', error);
          });
    })
}

// 关闭函数
const close = () => {
    visible.value = false;
};

defineExpose({ showBillToCheck })
</script>

